package com.atguigu.gulimall.seckill.scheduler;

import com.atguigu.common.constant.SeckillConstant;
import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SeckillSessionScheduler {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 * * * * *")
    public void uploadNewestSessions() {
        log.info("开始上架商品");
        RLock lock = redissonClient.getLock(SeckillConstant.SEC_KILL_UPLOAD_LOCK_CACHE_NAME);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadNewestSessions(3);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.forceUnlock();
        }
        log.info("上架商品完成");
    }
}
